<?php

/**
 * Add body classes if certain regions have content.
 */
function canvas_preprocess_html(&$variables) {
  if (!$variables['is_front']) {
    $path = drupal_get_path_alias($_GET['q']);
  }

  // Adjust the CSS classes for the following pages.
  if(isset($path)) {
    switch($path) {
      case 'maps':
        if(in_array('one-sidebar sidebar-second', $variables['classes_array'])) {
          $array_key = array_search('one-sidebar sidebar-second', $variables['classes_array']);
          unset($variables['classes_array'][$array_key]);
        }
        break;
    }
  }

  if (!empty($variables['page']['featured'])) {
    $variables['classes_array'][] = 'featured';
  }

  if (!empty($variables['page']['triptych_first'])
    || !empty($variables['page']['triptych_middle'])
    || !empty($variables['page']['triptych_last'])) {
    $variables['classes_array'][] = 'triptych';
  }

  if (!empty($variables['page']['footer_firstcolumn'])
    || !empty($variables['page']['footer_secondcolumn'])
    || !empty($variables['page']['footer_thirdcolumn'])
    || !empty($variables['page']['footer_fourthcolumn'])) {
    $variables['classes_array'][] = 'footer-columns';
  }

  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/ie6.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'IE 6', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css( path_to_theme() . '/js/jcarousel/skins/tango/skin.css' );

  //Plugins & Libraries
  drupal_add_js( path_to_theme() . '/js/cycle/jquery.cycle.min.js' );
  drupal_add_js( path_to_theme() . '/js/jcarousel/jquery.jcarousel.min.js' );
  drupal_add_js( path_to_theme() . '/js/jqbookmark/jqbookmark.js' );

  drupal_add_js( 'http://maps.google.com/maps/api/js?sensor=false' );

  //Global Behaviors
  drupal_add_js( path_to_theme() . '/js/behaviors/searchBox.js' );
  drupal_add_js( path_to_theme() . '/js/behaviors/slideshow.js' );
  drupal_add_js( path_to_theme() . '/js/behaviors/map.js' );

  # TODO
  # Figure out why this library is not loading on its own.
  drupal_add_library('contextual', 'contextual-links');
}

function canvas_js_alter(&$javascript) {
  // Swap out jQuery to use an updated version of the library
  //$javascript['misc/jquery.js']['data'] = path_to_theme() . '/js/jquery/jquery-1.6.4.js';
}

/**
 * Override or insert variables into the page template for HTML output.
 */
function canvas_process_html(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_html_alter($variables);
  }
}

/**
 * Implementation of hook_preprocess_page().
 */
function canvas_preprocess_page(&$vars, $hook) {

  // Variables that should always be sent to page templates.
  $vars['theme_path'] = drupal_get_path('theme', 'canvas');

  if(isset($vars['node'])) {
    switch($vars['node']->type) {
      case 'page':
        if(!empty($vars['node']->field_display_in)) {
          $channel_term = taxonomy_term_load($vars['node']->field_display_in['und'][0]['tid']);
          $vars['channel'] = strtolower(str_replace(' ', '_', $channel_term->name));
        }
        // Add custom theme suggestions to these Content Types.
        if(isset($vars['node']->field_template['und'])) {
          foreach($vars['node']->field_template['und'] as $template) {
            $vars['theme_hook_suggestions'][] = 'page__' . strtolower($template['taxonomy_term']->name);
          }
        }
        // On supported nodes, make the Channel's main content dynamic list
        // available.
        if(isset($vars['node']->field_channel_main_content_list['und'][0]['value'])) {
          if(isset($vars['node']->field_display_in['und'])) {
            $args = $channel_term->tid;
            $view = views_get_view('channel_main_content_list');
            $vars['page']['channel_main_content_list'] = $view->execute_display('block', $args);
          }
        }
        // Add the Monument List on the following pages.
        // TODO Set this dynamically from the Content Type itself.
        // TODO Determine how to send the number of results as an argument.
        if(!empty($vars['node']->field_display_in)) {
          $pages_allowed = array('maps');
          if(in_array(strtolower($channel_term->name), $pages_allowed)) {
            $vars['page']['monuments_list'] = views_get_view('monuments_list');
            $vars['page']['monuments_list']->execute('block_1');
          }
        }

        // Add the Related Object List on the following pages.
        if(!empty($vars['node']->field_display_in)) {
          $pages_allowed = array('maps');
          if(in_array(strtolower($channel_term->name), $pages_allowed)) {
            $vars['page']['related_objects'] = views_get_view('related_content');
            $vars['page']['related_objects']->execute('block_1');
          }
        }

        // Add additional information to the Maps Channel page.
        $vars['google_map'] = '';
        if(module_exists('gmapa') && isset($vars['node']->field_template['und'])) {
          if($vars['node']->field_template['und'][0]['taxonomy_term']->name == 'map') {
            $monuments = views_get_view('monuments_list');
            $monuments->execute('block_2');
            $vars['locations'] = array();
            $canvas = array('width' => 915, 'height' => 400, 'latitude' => 24, 'longitude' => 74);

            foreach($monuments->result as $row) {
              $location  = $row->_field_data['nid']['entity'];
              // Skip iteration if Art Object does not have both values.
              if(!(isset($location->field_latitude['und']) && isset($location->field_longitude['und']))) {
                continue;
              }
              $latitude  = $location->field_latitude['und'][0]['value'];
              $longitude = $location->field_longitude['und'][0]['value'];

              if($latitude && $longitude) {
                $locations[] = array(
                  'title' => $location->title,
                  'description' => t(strip_tags($location->body['und'][0]['value'])),
                  'latitude' => $location->field_latitude['und'][0]['value'],
                  'longitude' => $location->field_longitude['und'][0]['value'],
                );
              }
            }
            $vars['google_map'] = theme('mapa', array('canvas' => $canvas, 'locations' => $locations));
          }
        }
         // Add additional variable for the channel slideshow.
         // Get the view and pass tid in it because the view, for some strange reason cannot validate the term name  coming from Channel when it is implemented this way.
         // This should work fine Since vars[channel] is only available when field_display_in is avaialbe.
        $vars['channel_slideshow']="";
        if(!empty($vars['node']->field_display_in)) {
          $slidshow =   views_get_view('art_object_slideshow');
          $arg = $vars['node']->field_display_in['und'][0]['tid'];
          $slidshow = (!empty($slidshow)) ? $slidshow->execute_display($display_id = 'block_1',$arg) : '';
          $vars['channel_slideshow'] = (!empty($slidshow)) ? $slidshow['content'] : '';

        }
        break;
    }
  }
}

/**
 * Override or insert variables into the page template.
 */
function canvas_process_page(&$variables) {
  // Hook into color.module.
  if (module_exists('color')) {
    _color_page_alter($variables);
  }
  // Always print the site name and slogan, but if they are toggled off, we'll
  // just hide them visually.
  $variables['hide_site_name']   = theme_get_setting('toggle_name') ? FALSE : TRUE;
  $variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
  if ($variables['hide_site_name']) {
    // If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
    $variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
  }
  if ($variables['hide_site_slogan']) {
    // If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
    $variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
  // Since the title and the shortcut link are both block level elements,
  // positioning them next to each other is much simpler with a wrapper div.
  if (!empty($variables['title_suffix']['add_or_remove_shortcut']) && $variables['title']) {
    // Add a wrapper div using the title_prefix and title_suffix render elements.
    $variables['title_prefix']['shortcut_wrapper'] = array(
      '#markup' => '<div class="shortcut-wrapper clearfix">',
      '#weight' => 100,
    );
    $variables['title_suffix']['shortcut_wrapper'] = array(
      '#markup' => '</div>',
      '#weight' => -99,
    );
    // Make sure the shortcut link is the first item in title_suffix.
    $variables['title_suffix']['add_or_remove_shortcut']['#weight'] = -100;
  }
}

/**
 * Implements hook_preprocess_maintenance_page().
 canvastion canvas_preprocess_maintenance_page(&$variables) {
  if (!$variables['db_is_active']) {
    unset($variables['site_name']);
  }
  drupal_add_css(drupal_get_path('theme', 'canvas') . '/css/maintenance-page.css');
}

/**
 * Override or insert variables into the maintenance page template.
 */
function canvas_process_maintenance_page(&$variables) {
  // Variables that should always be sent to page templates.
  $variables['theme_path'] = drupal_get_path('theme', 'canvas');
  // Always print the site name and slogan, but if they are toggled off, we'll
  // just hide them visually.
  $variables['hide_site_name']   = theme_get_setting('toggle_name') ? FALSE : TRUE;
  $variables['hide_site_slogan'] = theme_get_setting('toggle_slogan') ? FALSE : TRUE;
  if ($variables['hide_site_name']) {
    // If toggle_name is FALSE, the site_name will be empty, so we rebuild it.
    $variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Drupal'));
  }
  if ($variables['hide_site_slogan']) {
    // If toggle_site_slogan is FALSE, the site_slogan will be empty, so we rebuild it.
    $variables['site_slogan'] = filter_xss_admin(variable_get('site_slogan', ''));
  }
  // Set body attributes
  $variables['attributes'] = 'bgcolor="#ffe8ac" marginwidth="0" marginheight="0"';
}

/**
 * Override or insert variables into the node template.
 */
function canvas_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }
}

/**
 * Override or insert variables into the block template.
 */
function canvas_preprocess_block(&$variables) {
  // In the header region visually hide block titles.
  if ($variables['block']->region == 'header') {
    $variables['title_attributes_array']['class'][] = 'element-invisible';
  }
}

/**
 * Implements theme_menu_tree().
 */
function canvas_menu_tree($variables) {
  return '<ul class="menu clearfix">' . $variables['tree'] . '</ul>';
}

/**
 * Implements theme_field__field_type().
 */
function canvas_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<h3 class="field-label">' . $variables['label'] . ': </h3>';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '<ul class="links inline">' : '<ul class="links">';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '<li class="taxonomy-term-reference-' . $delta . '"' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</li>';
  }
  $output .= '</ul>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . (!in_array('clearfix', $variables['classes_array']) ? ' clearfix' : '') . '">' . $output . '</div>';

  return $output;
}

function canvas_breadcrumb($variables){
  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
    // Adding the title of the current page to the breadcrumb.
    $breadcrumb[] = drupal_get_title();

    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '<h2 class="element-invisible">' . t('You are here') . '</h2>';

    $output .= '<div class="breadcrumb">' . implode(' > ', $breadcrumb) . '</div>';
    return $output;
  }
}
